#-*- coding:utf-8 -*-
import logging
import json
from rest_framework import permissions
from rest_framework.decorators import api_view, permission_classes
from rest_framework.exceptions import APIException
from rest_framework.response import Response
from rest_framework.views import exception_handler
from common_module.reception_handles.kaoala_reception_seach import kaoala_search_main

# Create your views here.
log = logging.getLogger('proscenium')


def custom_exception_handler(exc,context):
    '''
    2016-07-07  add by jack
    自定义处理系统异常抛出和view的异常抛出
    :param exc:
    :return:
    '''
    response = exception_handler(exc,context)
    if response is not None:
        response.data['state'] = response.status_code  #显示异常多加一个字段
        response.data['msg']=response.data.get('detail','')
        try:
            response.data.update(exc.data,context)
        except Exception,e:
            response.data['data']=''
        del response.data['detail']
    return response



class ServiceUnavailable(APIException):
    '''
    2016-07-07 add by jack
    自定义错误，用于在view来抛出
    state 错误码
    msg   返回提示信息
    kwargs  返回数据
    '''

    def __init__(self,state=200,msg=None,**kwargs):

        super(ServiceUnavailable,self).__init__(detail=msg)
        self.status_code=state
        self.data=kwargs










@api_view(['POST'])
@permission_classes((permissions.AllowAny,))
def kaoala_search(request):
    items={}
    items['state']=200
    items['msg']=u''
    items['data']={}
    search_text=request.POST.get('search_text','')
    flag=request.POST.get('flag','')   #0全部  1为题目 2为考点视频 3为互动 4试卷 5额外资源
    if flag not in ['0','1','2','3','4','5']:
        items['state']=204
        items['img']=u'标志位错误'
        log.info(u'搜索的结果 %s' %(json.dumps(items)))
        return Response(data=items)
    log.info(u'用户搜索的文本：%s' %search_text)
    kaoala_items=kaoala_search_main(search_text=search_text,flag=flag)
    items['data']=kaoala_items
    log.info(u'搜索的结果 %s' %(json.dumps(items)))
    return Response(data=items)

